package handler

import (
	"cloud-disk/core/internal/logic"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"crypto/md5"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"path"
)

func FileUploadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.FileUploadRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.Error(w, err)
			return
		}

		file, header, err := r.FormFile("file")
		if err != nil {
			httpx.Error(w, err)
			return
		}

		// 判断文件是否存在
		b := make([]byte, header.Size)
		_, err = file.Read(b)
		if err != nil {
			httpx.Error(w, err)
			return
		}

		hash := fmt.Sprintf("%x", md5.Sum(b))
		rp, byHash, err := svcCtx.RepositoryPoolModel.GetRepositoryPoolByHash(hash)
		if err != nil {
			httpx.Error(w, err)
			return
		}

		if byHash {
			item := types.FileUploadItem{
				Identity: rp.Identity,
				Ext:      rp.Ext,
				Name:     rp.Name,
			}
			httpx.OkJson(w, &types.FileUploadResponse{
				Message: "获取成功",
				Code:    200,
				Data:    item,
			})
			return
		}

		//chunk, err := tool.FileChunk(r)
		//if err != nil {
		//	httpx.OkJson(w, &types.FileUploadResponse{
		//		Message: "上传失败" + err.Error(),
		//		Code:    100,
		//	})
		//	return
		//}
		//
		//uploadId, key, err := svcCtx.Cos.InitiateMultipartUpload(r)
		//fmt.Println(uploadId)
		//if err != nil {
		//	httpx.OkJson(w, &types.FileUploadResponse{
		//		Message: "上传失败" + err.Error(),
		//		Code:    100,
		//	})
		//	return
		//}
		//
		//tags, err := svcCtx.Cos.UploadPart(uploadId, key, chunk)
		//if err != nil {
		//	httpx.OkJson(w, &types.FileUploadResponse{
		//		Message: "上传失败" + err.Error(),
		//		Code:    100,
		//	})
		//	return
		//}
		//time.Sleep(2 * time.Second)
		//fmt.Println(tags)
		//fmt.Println(key)
		//
		//url, err := svcCtx.Cos.CompleteMultipartUpload(uploadId, key, tags)
		//if err != nil {
		//	httpx.OkJson(w, &types.FileUploadResponse{
		//		Message: "上传失败 " + err.Error(),
		//		Code:    100,
		//	})
		//	return
		//}
		//fmt.Println(url)
		//return

		CosPath, err := svcCtx.Cos.CosUpload(r, svcCtx.Cos.Addr)
		if err != nil {
			httpx.OkJson(w, &types.FileUploadResponse{
				Message: "上传失败 " + err.Error(),
				Code:    100,
			})
			return
		}
		req.Name = header.Filename
		req.Size = int32(header.Size)
		req.Ext = path.Ext(header.Filename)
		req.Hash = hash
		req.Path = CosPath

		l := logic.NewFileUploadLogic(r.Context(), svcCtx)
		resp, err := l.FileUpload(&req)
		if err != nil {
			httpx.Error(w, err)
		} else {
			httpx.OkJson(w, resp)
		}
	}
}
